package com.ruoyi.place.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.city.domain.City;
import com.ruoyi.city.mapper.CityMapper;
import com.ruoyi.place.domain.MainAddress;
import com.ruoyi.place.mapper.PlaceMapper;
import com.ruoyi.provincial.domain.Provincial;
import com.ruoyi.provincial.mapper.ProvincialMapper;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.place.domain.Place;
import com.ruoyi.place.service.IPlaceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 基地管理Controller
 *
 * @author ruoyi
 * @date 2024-07-16
 */
@RestController
@RequestMapping("/place/place")
public class PlaceController extends BaseController {
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    private IPlaceService placeService;

    @Autowired
    PlaceMapper placeMapper;

    @GetMapping("/getMyPlaceId")
    public Long myPlaceId() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return placeMapper.selectPlaceByUserName(name).getId();
    }

    @GetMapping("/myPlace")
    public Object getStatus() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return placeMapper.selectPlaceByUserName(name);
    }

    @PreAuthorize("@ss.hasPermi('place:place:my')")
    @Log(title = "基地管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editMy")
    public AjaxResult editMyPlace(@RequestBody Place place) {
        Place place1 = placeMapper.selectPlaceByUserName(place.getUsername());
        if (place1 == null || Objects.equals(place1.getId(), place.getId())) {
            return toAjax(placeService.updatePlace(place));
        } else {
            return AjaxResult.error("该用户已有负责基地");

        }
    }

    @GetMapping("/myPlace/{id}")
    public AjaxResult myPlace(@PathVariable("id") Long id) {
        return success(placeService.selectPlaceById(id));
    }


    /**
     * 查询基地管理列表
     */
    @PreAuthorize("@ss.hasPermi('place:place:list')")
    @GetMapping("/list")
    public TableDataInfo list(Place place) {
        startPage();
        List<Place> list = placeService.selectPlaceList(place);
        return getDataTable(list);
    }

    /**
     * 导出基地管理列表
     */
    @PreAuthorize("@ss.hasPermi('place:place:export')")
    @Log(title = "基地管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Place place) {
        List<Place> list = placeService.selectPlaceList(place);
        ExcelUtil<Place> util = new ExcelUtil<Place>(Place.class);
        util.exportExcel(response, list, "基地管理数据");
    }

    /**
     * 获取基地管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('place:place:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(placeService.selectPlaceById(id));
    }

    /**
     * 新增基地管理
     */
    @PreAuthorize("@ss.hasPermi('place:place:add')")
    @Log(title = "基地管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Place place) {
        Place place1 = placeMapper.selectPlaceByUserName(place.getUsername());
        if (place1 == null || Objects.equals(place1.getId(), place.getId())) {
            return toAjax(placeService.insertPlace(place));
        } else {
            return AjaxResult.error("该用户已有负责基地");

        }
    }

    /**
     * 修改基地管理
     */
    @PreAuthorize("@ss.hasPermi('place:place:edit')")
    @Log(title = "基地管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Place place) {
        Place place1 = placeMapper.selectPlaceByUserName(place.getUsername());
        if (place1 == null || place1.getId() == place.getId()) {
            return toAjax(placeService.updatePlace(place));
        } else {
            return AjaxResult.error("该用户已有负责基地");

        }
    }

    /**
     * 删除基地管理
     */
    @PreAuthorize("@ss.hasPermi('place:place:remove')")
    @Log(title = "基地管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(placeService.deletePlaceByIds(ids));
    }


    @Autowired
    private ProvincialMapper provincialMapper;

    @Autowired
    private CityMapper cityMapper;

    @GetMapping("/getAllAddress")
    public List<MainAddress> getProvincialWithCities() {
        List<Provincial> provincials = provincialMapper.selectProvincialList(null);
        List<MainAddress> mainAddresses = new ArrayList<>();

        provincials.forEach(provincial -> {
            List<City> cities = cityMapper.selectCityByPId(provincial.getId());
            List<MainAddress> children = new ArrayList<>();
            for (City city : cities) {
                MainAddress mainAddress = new MainAddress();
                mainAddress.setValue(city.getId());
                mainAddress.setLabel(city.getCity());
                children.add(mainAddress);
            }

            MainAddress mainAddress = new MainAddress();
            mainAddress.setChildren(children);
            mainAddress.setValue(provincial.getId());
            mainAddress.setLabel(provincial.getProvincial());
            mainAddresses.add(mainAddress);
        });

        return mainAddresses;
    }
}
